package com.wandian.cqcsk.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

import com.mylib.libcore.AppContext;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.mylib.libcore.config.AppConfig.WX_APP_ID;

/**
 * @author Administrator
 * @date 2019/12/20-23:37
 * @description
 **/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {


    private IWXAPI api;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

//        setContentView(R.layout.activity_wx_layout);
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }



    //请求回调结果处理
    @Override
    public void onResp(BaseResp baseResp) {
        //登录回调
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Log.d("BaseResp==",""+ JsonUtil.toJson(baseResp));
                if(!UIUtils.isEmpty(baseResp)){
                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("wx_result",JsonUtil.toJson(baseResp)+"");
                }
                finish();
                break;
//            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
//            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
            default:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {

        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(WX_APP_ID)
                .append("&secret=")
                .append("WX_AppSecret")
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        Log.d("urlurl", loginUrl.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("wxLogin=", "onFailure: ");

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo= response.body().string();
                Log.d("wxLogin=", "onResponse: " +responseInfo);
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                getUserInfo(access, openId);
            }
        });
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //通过JSON解析获取access和token值，再通过getUserInfo(access, openId)方法获取用户信息
    private void getUserInfo(String access, String openid) {
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openid;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(getUserInfoUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("wxLogin=", "onFailure: ");


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo= response.body().string();
                Log.d("wxLogin=onResponse", "onResponse: " + responseInfo);

                if (!UIUtils.isEmpty(responseInfo)){
                    try {
//                "openid":"oPrS70VdTVLuJ0emMADRebtlwwBk",
//                        "nickname":"海的天空",
//                        "sex":1,
//                        "language":"zh_CN",
//                        "city":"Jiangjin",
//                        "province":"Chongqing",
//                        "country":"CN",
//                        "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIo4vA3JFO6CsUXk17HqpB6IhtSqibCMj16yiaodomDuhxFvEIibppWBMhAgL2UAeOfVSIcGaJdEhlQg/132",
//                        "privilege":[],
//                "unionid":"o62SkjkvEvOaMCGkgBHI2ayMtk78"
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userWxInfo",responseInfo);
                        JSONObject jsonObject = new JSONObject(responseInfo);
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userName",jsonObject.getString("nickname")+"");
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userHeadImg",jsonObject.getString("headimgurl")+"");
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userSex",jsonObject.getString("sex")+"");
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userWxOpenId",jsonObject.getString("openid")+"");
                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("userWxUnionId",jsonObject.getString("unionid")+"");

                        finish();
                    } catch (JSONException e) {
                        ToastUtil.show("微信授权异常");
                        finish();
                        e.printStackTrace();
                    }
                }

            }
        });
    }

}
